<?php
class movie_parser
{
    public static function get_movie($id, $lang='en', $xml=true)
    {
        //XPATHS
        $movieXpath['title'] = '//span[@itemprop="name"]';
        $movieXpath['original_title'] = '//h1[@itemprop="name"]/span[@class="title-extra"]';
        $movieXpath['year'] = '//span[@class="nobr"]';
        $movieXpath['rating'] = '//div[@class="titlePageSprite star-box-giga-star"]';
        $movieXpath['votes'] = '//span[@itemprop="ratingCount"]';
        $movieXpath['release'] = '//a[@title="See all release dates"]';
        $movieXpath['runtime'] = '//time[@itemprop="duration"]';
        $movieXpath['poster'] = '//td[@id="img_primary"]//img';
        $movieXpath['description'] = '//p[@itemprop="description"]';
        $movieXpath['storyline'] = '//div[@id="titleStoryLine"]//p';
        $movieXpath['images'] = '//div[@class="mediastrip"]//img';
        $movieXpath['directors'] = '//a[@itemprop="director"]';
        $movieXpath['genres'] = '//div[@class="infobar"]//a/span[@itemprop="genre"]';
        $movieXpath['numactors'] = '//table[@class="cast_list"]//tr';
        $movieXpath['actorimg'] = '//table[@class="cast_list"]//tr[{0}]/td[1]/a/img';
        $movieXpath['actorname'] = '//table[@class="cast_list"]//tr[{0}]/td[2]';
        $movieXpath['actorid'] = '//table[@class="cast_list"]//tr[{0}]/td[2]/a';
        $movieXpath['actorrole'] = '//table[@class="cast_list"]//tr[{0}]/td[4]';
        $movieXpath['mode'] = '//div[@class="infobar"]';

//for TV EPISODE to retrieve series title and SxxExx number
        $movieXpath['series_title'] = '//h2[@class="tv_header"]/a';
        $movieXpath['episode_number'] = '//h2[@class="tv_header"]/span';

//get movie url
        $imdburl = 'http://www.imdb.com/title/' . $id;


//echo $file;

//prepare DOMDocument
        $html = new DOMDocument();
        @$html->loadHTML(udnutil::read_url($imdburl));


        $xpath = new DOMXPath($html);

//DATA INFO
        $movie['titleonly'] = movie_parser::clean(movie_parser::getFirstNode($xpath, $movieXpath['title']));
        $movie['year'] = movie_parser::clean(movie_parser::getFirstNode($xpath, $movieXpath['year']));
        $movie['title'] = $movie['titleonly']. ' ' . $movie['year'];
        $movie['urltitle'] = preg_replace('#[^a-zA-Z]#', '', str_replace(' ','-',$movie['titleonly']));

        $movie['original_title'] = movie_parser::clean(movie_parser::getFirstNode($xpath, $movieXpath['original_title']));
        $movie['rating'] = movie_parser::clean(movie_parser::getFirstNode($xpath, $movieXpath['rating']));
        $movie['votes'] = movie_parser::clean(movie_parser::getFirstNode($xpath, $movieXpath['votes']));
        $movie['release'] = movie_parser::clean(movie_parser::getFirstNode($xpath, $movieXpath['release']));
        $movie['runtime'] = movie_parser::clean(movie_parser::getFirstNode($xpath, $movieXpath['runtime']));
        $movie['poster'] = movie_parser::clean(movie_parser::parseAttribute($xpath, $movieXpath['poster'], "src"));
        $movie['large_poster'] = udnutil::originalImdbImage(movie_parser::clean(movie_parser::parseAttribute($xpath, $movieXpath['poster'], "src")));

        $movie['description'] = movie_parser::clean(movie_parser::getFirstNode($xpath, $movieXpath['description']));
        $movie['storyline'] = movie_parser::clean(movie_parser::getFirstNode($xpath, $movieXpath['storyline']));
        $movie['mode'] = (strpos(movie_parser::getFirstNode($xpath, $movieXpath['mode']), 'TV Series') !== false) ?
            "tv-series" : "movie";

        if ($movie['mode'] == 'movie') {
            $movie['mode'] = (strpos(movie_parser::getFirstNode($xpath, $movieXpath['mode']), 'TV Episode') !== false) ?
                "tv-episode" : "movie";
        }
        if ($movie['mode'] == 'tv-series') {
            $series_name = substr($movie['title'], 0, strpos($movie['title'], '(') - 1);
            $movie['torrent_title'] = $series_name . ' Season';
        } else if ($movie['mode'] == 'tv-episode') {
            $series_name = movie_parser::clean(movie_parser::getFirstNode($xpath, $movieXpath['series_title']));
            //$series_name = str_replace(' ','.',$series_name);
            $pcs = explode(' ', movie_parser::getFirstNode($xpath, $movieXpath['episode_number']));
            $snum = str_replace(',', '', $pcs[1]);
            $snum = strlen($snum) < 2 ? '0' . $snum : $snum;
            $enum = $pcs[3];
            $enum = strlen($enum) < 2 ? '0' . $enum : $enum;
            $seasonEpisode = 'S' . $snum . 'E' . $enum;
            $movie['torrent_title'] = $series_name . ' ' . $seasonEpisode;
        } else {
            $movie['torrent_title'] = udnutil::fixAccents( $movie['title']);

        }

//DATA IMAGES
        $images = array();
        $imagesList = movie_parser::parse($xpath, $movieXpath['images']);
        $i = 0;
        foreach ($imagesList as $image) {
            $images[$i]['thumbnail'] = $image->getAttribute('loadlate');
            $images[$i]['original'] = udnutil::originalImdbImage($image->getAttribute('loadlate'));
            $i++;
        }
        $movie['images'] = $images;

//DATA GENRES
        $genres = array();
        $genresList = movie_parser::parse($xpath, $movieXpath['genres']);
        $i = 0;
        foreach ($genresList as $genre) {
            $genres[$i] = $genre->nodeValue;
            $i++;
        }
        $movie['genres'] = $genres;

//DATA DIRECTORS
        $directors = array();
        $directorsList = movie_parser::parse($xpath, $movieXpath['directors']);
        $i = 0;
        foreach ($directorsList as $director) {
            $directors[$i] = $director->nodeValue;
        }
        $movie['directors'] = $directors;

//DATA ACTORS
        $actors = array();
        $nodelist = movie_parser::parse($xpath, $movieXpath['numactors']);
        $length = $nodelist->length;
        $j = 0;
        for ($i = 2; $i <= $length && $i < 11; $i++) { //limit number of actors to return
            $imgxpath = str_replace("{0}", $i, $movieXpath['actorimg']);
            $img = movie_parser::parseAttribute($xpath, $imgxpath, "loadlate");
            if ($img == null || $img == "") {
                $img = movie_parser::parseAttribute($xpath, $imgxpath, "src");
            }


            $idxpath = str_replace("{0}", $i, $movieXpath['actorid']);
            $actorid = movie_parser::parseAttribute($xpath, $idxpath, 'href');
            $actorid = explode('/', $actorid);
            $actorurl = 'transform?personid=' . $actorid[2];


            $namexpath = str_replace("{0}", $i, $movieXpath['actorname']);
            $actorname = movie_parser::getFirstNode($xpath, $namexpath);


            $rolexpath = str_replace("{0}", $i, $movieXpath['actorrole']);
            $role = movie_parser::getFirstNode($xpath, $rolexpath);

            $actor['img'] = $img;
            $actor['name'] = trim($actorname);
            $actor['role'] = $role;
            $actor['actorurl'] = $actorurl;
            $actors[$j] = $actor;
            $j++;
        }
        $movie['actors'] = $actors;

//get similar movies here
        $movie['similar'] = movie_parser::getSimilarMovies($id);

        $movie['reviews'] = movie_parser::getReviews($id);
        $movie['seasons'] = array();
        if ($movie['mode'] == 'tv-series')
            $movie['seasons'] = movie_parser::getSeasons($id);

        if(false && $lang == 'ar')
        {
            $google = strpos('googlebot', strtolower($_SERVER['HTTP_USER_AGENT'])) !== FALSE;
            //arabic translation
            if($google)
                $movie_str = $movie['title'].' | '.$movie['description'];
            else
                $movie_str = $movie['title'].' | '.$movie['description'].' | '.$movie['storyline'];
/*
            foreach($movie['actors'] as $act)
                $movie_str.= ' | '.$act['name'];
*/
            $movie_str = lang::translate($movie_str);

            $pcs = explode('|',$movie_str);

            $movie['title_lang'] = $pcs[0];
            $movie['description'] = $pcs[1];
            if(!$google)
                $movie['storyline'] = $pcs[2];
/*
            for($i=3; $i<count($movie['actors'])+3; $i++)
            {
                $movie['actors'][$i-3]['name'] = trim($pcs[$i]);
            }
*/

        }

        if($xml)
            return movie_parser::TestBlockHTML($movie, $id);
        else
            return $movie;
    }



//FUNCTION FOR SIMILAR MOVIES
    public static function getSimilarMovies($id)
    {
        $movies = array();
        $imdbUrl = "http://www.imdb.com/widget/recommendations/_ajax/get_more_recs?caller_name=p13nsims-title&count=25&specs=p13nsims%3A" . $id . "&start=0";

        $json = udnutil::read_url($imdbUrl);

        $result = json_decode($json, TRUE);
        $i = 0;
        if($result['recommendations'])
            foreach ($result['recommendations'] as $item) {
                //echo str_replace(":","",$item['content']);
                //exit();
                $movie['id'] = $item['tconst'];

                $html = new DOMDocument();
                $html->loadHTML($item['content']);
                $xpath = new DOMXPath($html);

                $tempNode = $xpath->query('//img[@class="rec_poster_img"]')->item(0);
                $image = "";
                if ($tempNode != null) {
                    $title = $tempNode->getAttribute('title');
                    $image = $tempNode->getAttribute('src');
                    //$pieces = explode("url(",$image);
                    //$pieces = explode(');',$pieces[1]);
                    //$image = $pieces[0];

                    $image = udnutil::scaleImdbImage($image, 2);


                }

                $movie['poster'] = $image;
                $movie['title'] = utf8_decode($title);

                $movies[$i] = $movie;
                $i++;
            }
        return $movies;
    }

//FUNCTION FOR REVIEWS
    public static function getReviews($id)
    {

        $imdbUrl = "http://www.imdb.com/title/$id/reviews?filter=best&spoiler=hide";

        $content = udnutil::read_url($imdbUrl);
        //prepare DOMDocument
        $html = new DOMDocument();
        @$html->loadHTML($content);
        $xpath = new DOMXPath($html);

        $nodes = $xpath->query('//div[@id="tn15content"]//p');
        $reviews = array();

        if ($nodes->length > 0) {
            $j = 0;
            for ($i = 0; $i < $nodes->length - 1 && $i < 6; $i += 2) { //return only 3 max reviews
                $review['rating'] = "";
                $review['summary'] = $xpath->query('b', $nodes->item($i))->item(0)->nodeValue;
                $review['summary'] = movie_parser::clean($review['summary']);
                $review['text'] = $html->saveXML($nodes->item($i + 1));
                $review['text'] = str_replace('&', '&amp;', $review['text']);
                $reviews[$j] = $review;
                $j++;
            }
        }


        return $reviews;
    }

//FUNCTION FOR SEASON
    public static function getSeasons($id)
    {
        $url = "http://www.imdb.com/title/" . $id . "/episodes";
        $seasons = array();
        $xp = '//select[@id="bySeason"]/option';

        $content = udnutil::read_url($url);

        //prepare DOMDocument
        $html = new DOMDocument();
        @$html->loadHTML($content);
        $xpath = new DOMXPath($html);

        $seasonsList = $xpath->query($xp);
        $i = $seasonsList->length - 1;
        foreach ($seasonsList as $season) {
            $seasons[$i] = $season->getAttribute('value');
            $i--;
        }

        return $seasons;
    }


//STATIC FUNCTIONS
    public static function parse($xpath, $tag)
    {
        $nodelist = $xpath->query($tag);
        return $nodelist;
    }

    public static function getFirstNode($xpath, $tag)
    {
        $nodelist = movie_parser::parse($xpath, $tag);
        return $nodelist->item(0)->nodeValue;
    }

    public static function parseAttribute($xpath, $tag, $attribute)
    {
        $nodelist = movie_parser::parse($xpath, $tag);
        if ($nodelist->length > 0) {
            //echo $nodelist->item(0)->nodeValue.$nodelist->item(0)->getAttribute($attribute)."<br />";
            return $nodelist->item(0)->getAttribute($attribute);
        } else
            return "";
    }

    public static function clean($value)
    {

        return trim(preg_replace("/[\n\r]/", "", $value));
    }

    public static function TestBlockHTML($movie, $id)
    {
        ob_start(); ?>
    <movie>
        <mode><?echo $movie['mode']?></mode>
        <imdb><?echo $id?></imdb>
        <trailer><?echo $movie['trailer']?></trailer>
        <title><?echo $movie['title']?></title>
        <urltitle><?echo str_replace(' ', '-', $movie['title'])?></urltitle>
        <torrent_title><?echo $movie['torrent_title']?></torrent_title>
        <year><?echo $movie['year']?></year>
        <poster scaled="<?echo udnutil::originalImdbImage($movie['poster'])?>"><?echo $movie['poster']?></poster>
        <tiny_poster><?echo udnutil::smallImdbImage($movie['poster'])?></tiny_poster>
        <rating><?echo $movie['rating']?></rating>
        <votes><?echo $movie['votes']?></votes>
        <release><?echo $movie['release']?></release>
        <runtime><?echo $movie['runtime']?></runtime>
        <description><?echo $movie['description']?></description>
        <images><?foreach ($movie['images'] as $image) { ?>
            <image scaled="<?echo $image['original']?>"><?echo $image['thumbnail']?></image><? }?></images>
        <genres><?foreach ($movie['genres'] as $genre) { ?>
            <genre><?echo $genre?></genre><? }?></genres>
        <directors><?foreach ($movie['directors'] as $director) { ?>
            <director><?echo $director?></director><? }?></directors>
        <cast><?foreach ($movie['actors'] as $actor) { ?>
            <actor pic="<?echo movie_parser::clean($actor['img'])?>" name="<?echo movie_parser::clean($actor['name'])?>"
                   actorurl="<?echo movie_parser::clean($actor['actorurl'])?>"
                   role="<?echo movie_parser::clean($actor['role'])?>"/><? }?></cast>
        <similar>
            <?foreach ($movie['similar'] as $m) { ?>
            <movie>
                <id><?echo $m['id']?></id>
                <title><?echo $m['title']?></title>
                <urltitle><?echo str_replace(' ', '-', $m['title'])?></urltitle>
                <poster><?echo 'http://5.34.247.14/dl/' . $m['poster']?></poster>
            </movie>
            <? }?>
        </similar>
        <reviews>
            <?foreach ($movie['reviews'] as $rv) { ?>
            <review>
                <rating><?echo $rv['rating']?></rating>
                <summary><?echo $rv['summary']?></summary>
                <text><?echo $rv['text']?></text>
            </review>
            <? }?>
        </reviews>

        <seasons>
            <?foreach ($movie['seasons'] as $s) { ?>
            <season><?echo $s?></season>
            <? }?>
        </seasons>
    </movie>
    <?php return ob_get_clean();
    }
}

?>